<template>
  <div>
    <el-form ref="formRef" :model="formData" label-width="100px" :rules="formRules">
      <el-row :gutter="22">
        <el-col :span="12">
          <el-form-item label="节点名称" prop="node_name">
            <el-input
              v-model="formData.node_name"
              type="text"
              autoComplete="off"
              placeholder="请输入节点名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="节点密码" prop="password">
            <input-pwd v-model="formData.password" />
          </el-form-item>
        </el-col>
      </el-row>
      <p class="tip">注：此处为hacluster用户密码！</p>
    </el-form>

    <div class="dialog-footer">
      <el-button @click="handleDialogClose">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
    </div>
  </div>
</template>

<script>
import InputPwd from '@/components/InputPwd.vue'
import { addCluster } from '@/api/clusterOverview'
import { vd } from '@/utils/validate'

export default {
  name: 'AddCluster',
  components: {
    InputPwd,
  },
  data() {
    return {
      formData: {
        node_name: '',
        password: '',
      },
      formRules: {
        node_name: [vd.required, vd.length(1, 50), vd.nodeName],
        password: [vd.required, vd.length(8, 50), vd.pwd],
      },
      loading: false,
    }
  },
  methods: {
    // 表单提交
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.loading = true
          addCluster(this.formData)
            .then((res) => {
              this.loading = false
              if (res.data.action) {
                this.$message.success(res.data.info || '添加集群成功')
                this.$emit('click', 'success')
              } else {
                this.$message.error(res.data.error || '添加集群失败')
                this.$emit('click')
              }
            })
            .catch((err) => {
              this.loading = false
              console.error('添加集群失败:', err)
              this.$message.error('添加集群失败')
              this.$emit('click')
            })
        }
      })
    },

    // 取消
    handleDialogClose() {
      // 重置表单
      this.$refs.formRef.resetFields()
      this.$emit('click')
    },
  },
}
</script>

<style lang="scss" scoped>
.tip {
  color: #f5222d;
  font-size: 12px;
  line-height: 1.5;
  margin-top: -10px;
  margin-bottom: 10px;
  padding-left: 100px;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}
</style>
